﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace EnterpriseLibraryExtensions.Services.Mapping
{
    internal class ListCollectionHandler : ICollectionHandler
    {
        private readonly Type _targetElementType;
        private readonly List<object> _list = new List<object>();

        public ListCollectionHandler(Type targetElementType)
        {
            _targetElementType = targetElementType;
        }

        public void AddElement(object element)
        {
            _list.Add(element);
        }

        public object CreateInstance()
        {
            var newType = typeof(List<>);
            var genericType = newType.MakeGenericType(_targetElementType);
            var instance = (IList)Activator.CreateInstance(genericType);

            _list.ForEach(e => instance.Add(e));

            return instance;
        }
    }
}
